﻿using DeHeng_Mes.Model.ConfigModel;
using DeHeng_Mes.Model.Table;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DeHeng_Mes.Model.Singleton
{
    public sealed class ErrorDic
    {
        // 线程安全的缓存（Key: 报警ID, Value: 报警信息）
        private static readonly ConcurrentDictionary<int, string> _alarmCache = new ConcurrentDictionary<int, string>();

        // 私有构造函数（确保单例）
        private ErrorDic() { }

        // 获取所有报警（返回只读副本，避免外部修改）
        public static IReadOnlyDictionary<int, string> GetAllAlarms()
        {
            return new ReadOnlyDictionary<int, string>(_alarmCache);
        }

        // 添加报警
        public static bool AddAlarm(int alarmId, string alarmMessage)
        {
            return _alarmCache.TryAdd(alarmId, alarmMessage);
        }

        // 移除报警
        public static bool RemoveAlarm(int alarmId)
        {
            lock (_alarmCache)
            {
                bool v = _alarmCache.TryRemove(alarmId, out _);

                return v;
            }
        }

        /// <summary>
        /// 通过 errorMessage 反向查找 id
        /// </summary>
        /// <param name="errorMessage"></param>
        /// <returns></returns>
        public static int GetAlarmIdByMessage(string errorMessage)
        {
            // 遍历缓存，查找匹配 errorMessage 的 id
            foreach (var alarm in _alarmCache)
            {
                if (alarm.Value.Equals(errorMessage))
                    return alarm.Key;
            }
            return 0;
        }
    }
}
